package com.example.glgk.controller.report;

import com.example.glgk.dto.UserInfo;
import com.example.glgk.dto.report.*;
import com.example.glgk.entity.report.ReportEntity;
import com.example.glgk.entity.report.ReportTaskEntity;
import com.example.glgk.entity.report.TaskEntity;
import com.example.glgk.optionenum.ProcessStatus;
import com.example.glgk.optionenum.TaskStatus;
import com.example.glgk.service.report.ReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * @author lxk
 * <p>指标上报controller</p>
 */
@Api(tags = "指标上报controller")
@Slf4j
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/ReportController")
public class ReportController {

    @Autowired
    private ReportService reportService;

    @PostMapping("/save")
    @ApiOperation(value = "指标上报保存")
    public List<ReportEntity> save(@RequestBody List<ReportDto> reportDtos){
        return  reportService.save(reportDtos);
    }

    @PostMapping("/submit")
    @ApiOperation(value = "指标上报提交")
    public boolean submit(@RequestBody List<ReportDto> reportDtos){
        return reportService.submit(reportDtos);
    }

    @PostMapping("/operation")
    @ApiOperation(value = "指标上报审批")
    public void operation(@RequestBody List<ReportDto> reportDtos){
        reportService.operation(reportDtos);
    }

    @PostMapping("/getTask")
    @ApiOperation(value = "查询任务页面")
    public List<ReportTaskDto> getTask(@RequestBody TaskSearchDto taskSearchDto){
        return reportService.getTask(taskSearchDto);
    }

    @PostMapping("/getTaskNames")
    @ApiOperation(value = "查询上报任务名称列表")
    public List<String> getTaskNames(@RequestBody UserInfo userInfo){
        return reportService.getTaskNames(userInfo);
    }

    @PostMapping("/search")
    @ApiOperation(value = "指标上报默认填充")
    public List<ReportDto> search(@RequestBody ReportSearchDto search){
        return reportService.searchPlus(search);
    }


    @PostMapping("/searchHistory")
    @ApiOperation(value = "查询历史记录")
    public List<OperationHistoryDto> searchHistory(@RequestParam("taskId") Integer taskId){
        return reportService.searchHistory(taskId);
    }


    @GetMapping("/searchRejectHistory")
    @ApiOperation(value = "查询驳回的历史记录")
    public List<OperationHistoryDto> searchRejectHistory(@RequestParam("taskId") Integer taskId){
        return reportService.searchRejectHistory(taskId);
    }



    @PostMapping("/cancel")
    @ApiOperation(value = "指标上报撤销")
    public void cancel(@RequestBody List<ReportDto> reportDtos){
        reportService.cancel(reportDtos);
    }


    @PostMapping("/upload")
    @ApiOperation(value = "附件文件上传")
    public String upload(@RequestParam("file") MultipartFile[] files,@RequestParam("userId") String userId, @RequestParam("deptId")String deptId,@RequestParam("khzb")String khzb) throws Exception {
        return reportService.upload(files,userId,deptId,khzb);
    }

    @PostMapping("/getIndicator")
    @ApiOperation(value = "下拉查询56项指标")
    public List<Map<String,String>> getIndicator(){
        return reportService.getIndicator();
    }

    @PostMapping("/queryFj")
    @ApiOperation(value = "查询佐证材料")
    public List<Map<String,String>> queryFj(@RequestParam("deptId") String deptId
            , @RequestParam("years") List<String> years, @RequestParam("taskNames") List<String> taskNames){
        return reportService.queryFj(deptId, years, taskNames);
    }

    @PostMapping("/queryAttachments")
    @ApiOperation(value = "查询附件材料")
    public List<Map<String,String>> queryAttachments(@RequestParam("list") List<String> list){
        return reportService.queryAttachments(list);
    }


    @PostMapping("/files")
    @ApiOperation(value = "文件预览")
    public ResponseEntity<Resource> downloadFile(@RequestParam("curFilePath") String curFilePath,@RequestParam("fileName") String fileName) throws Exception {

        String absolutePath = Paths.get("").toAbsolutePath().toString(); // 获取当前工作目录的绝对路径
        Path filePath = Paths.get(absolutePath,curFilePath, fileName).normalize(); // 构建绝对路径

        Resource resource = new PathResource(filePath);
        if (!resource.exists()) {
            throw new Exception("文件不存在！");
        }
        String encodedFilename = URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8.name());


        String[] split = fileName.split("\\.");
        HttpHeaders headers = new HttpHeaders();
        //todo 建议搞个数组或者集合判断
        if ("jpg".equals(split[1]) || "png".equals(split[1])) {
            headers.setContentType(MediaType.IMAGE_PNG);
        }else if ("xlsx".equals(split[1]) || "xls".equals(split[1])){
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }else if ("docx".equals(split[1]) || "doc".equals(split[1])){
            headers.setContentType(MediaType.parseMediaType("application/msword"));
        }else if ("pdf".equals(split[1]) || "txt".equals(split[1])){
            headers.setContentType(MediaType.APPLICATION_PDF);
        }

        ResponseEntity<Resource> body = ResponseEntity.ok()
                .headers(headers)
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename)
                .body(resource);
        return body;
    }


    @GetMapping("/getDataSource")
    @ApiOperation(value = "数据接取系统名称")
    public List<String> getDataSource(){
        return reportService.getDataSource();
    }


}